import { Context, Application } from 'egg';
import ResponseBody from '@app/common/ResponseBody';
import { ReturnCodeChzh, ReturnCodeEnum } from '@app/types/response';

export default function (_option: any, _app: Application) {
  return async function baseIO(_ctx: Context, next: () => any) {
    try {
      await next();
      if (_ctx.status == 404) {
        _ctx.realStatus = 404;
        // 置空
        delete _ctx.body;
      }
    } catch (error) {
      let err = error as any;
      if (!(error instanceof ResponseBody)) {
        err = new ResponseBody({ code: ReturnCodeEnum.Fail, msg: err.message || ReturnCodeChzh[ReturnCodeEnum.Fail] })
      }
      _ctx.realStatus = err.code;
      _ctx.status = err.code;
      _ctx.body = err;
    }
  };
}
